package com.ezcoding.engine;

import com.ezcoding.model.*;
import com.ezcoding.utils.StatusUtil;
import com.ezcoding.utils.Tools;

import java.util.List;
import java.util.Map;

public class PurchaseBackCalculator extends BaseDingdanCalculator {

    public PurchaseBackCalculator(Dingdan dingdan, List<DingdanDetail> details) {
        super(dingdan, details);
    }

    @Override
    public boolean checkProductStore(int curCount, int needCount) {
        return curCount >= needCount;
    }

    @Override
    public double getCurTicket(double curValue) {
        if (dingdan.getIsTicket() == 1) {
            //不开票
            return 0;
        }

        return curValue * -1;
    }

    @Override
    public double getCurMoney(double curValue) {
        return curValue * -1;
    }

    @Override
    public void setDetailTicket(DingdanDetail detail, double value) {
        detail.setTicketIn(value);
    }

    @Override
    public void setDetailMoney(DingdanDetail detail, double value) {
        detail.setMoneyOut(value);
    }

    @Override
    public void setTicket(double value) {
        dingdan.setTicketIn(value);
    }

    @Override
    public void setMoney(double value) {
        dingdan.setMoneyOut(value);
    }

    @Override
    public double getTotalMoney() {
        return dingdan.getSourceFreightUnpaid() - dingdan.getTargetFreightPaid() + dingdan.getFreeMoney() + dingdan.getMoney();
    }

    @Override
    public void updateCompanyInfo() {
        Company company = getCompany();

        company.setTotalTicket(company.getTotalTicket() - dingdan.getTicket());
        company.setTotalMoney(company.getTotalMoney() - dingdan.getSourceFreightPaid() - dingdan.getTargetFreightPaid() + dingdan.getMoney());
    }

    @Override
    public Map<String, Object> updateRelatedDingdanInfo() {
        return StatusUtil.getSuccessStatusWithEmptyMessage();
    }

    @Override
    public int getRelationType() {
        return UserRelation.RELATION_TYPE_GIVER;
    }

    @Override
    public void updateProductStore(Product product, int needCount) {
        product.setCount(product.getCount() - needCount);
    }

    @Override
    public void updateProductAndDetail(Product product, DingdanDetail detail) {
        updateProductInPrice(product, detail);
        updateProductStore(product, detail.getCount());
    }

    @Override
    public void updateProfit(DingdanDetail detail, double inPrice) {

    }

    @Override
    public void updateProductInPrice(Product product, DingdanDetail detail) {
        double totalMoney = product.getCount() * product.getInPrice() - detail.getCount() * detail.getPrice() / getTaxRate();
        int totalCount = product.getCount() - detail.getCount();
        if (totalCount == 0) {
            product.setInPrice(0.0);
            return;
        }
        product.setInPrice(Tools.formatDouble(totalMoney / totalCount));
    }
}
